<?php

/*
 * Author: Quan Van Sinh
 * Email: sinhvnb@vietnambiz.com
 */

function get_geo_by_parent_id($id) {
    global $db_ancu;
    $sql = "SELECT * FROM geographic  WHERE geo_parent = $id ";
    return $rst = $db_ancu->query($sql);
}

// get all city in db ancu
function get_all_city() {
    global $db_ancu;
    $sql = "SELECT geo_id,geo_title FROM geographic WHERE geo_id>3 AND geo_parent =1 OR geo_parent = 2 OR geo_parent = 3 ORDER BY geo_id ASC";
    $rs = $db_ancu->query($sql);
    return $rs;
}

// get menu con cho du an ---header bantin
function get_all_cate_project() {
    global $db_ancu;
    $sql = "SELECT * FROM cat_project  WHERE cat_id != 9";
    return $rs = $db_ancu->query($sql);
}

function get_box_relative($art_cat_id, $relate_for) {
    global $db, $config;
    $result = false;

    $rs = $db->query_first("SELECT * FROM box_relation WHERE art_cat_id='$art_cat_id' AND relate_for='$relate_for' AND active=1");
    if ($rs) {
        $result['title'] = $rs['box_title'];
        $result['view_type'] = $rs['view_type'];
        if ($rs['view_type'] == 'html') {
            $result['value'] = $rs['value'];
        } elseif ($rs['view_type'] == 'article') {
            $arrAId = $rs['value'];
            $rsArticle = $db->query("SELECT * FROM article WHERE id IN ($arrAId) AND status='yes'");
            $result['value'] = $rsArticle;
        }
    }
    return $result;
}

// Function to remove HTML tags, Javascript,...
function filter($str) {
    $str = trim($str);
    $str = mysql_real_escape_string($str);
    $search = array("'<'", // Strip out javascript
        "'>'",
        "'[\/\!]*?[^<>]*?>'si", // Strip out html tags
        "'([\r\n])[\s]+'", // Strip out white space
        "'&(quote|#34);'i", // Replace html entities
        "'&(amp|#38);'i",
        "'&(lt|#60);'i",
        "'&(gt|#62);'i",
        "'&(nbsp|#160);'i",
        "'&(iexcl|#161);'i",
        "'&(cent|#162);'i",
        "'&(pound|#163);'i",
        "'&(copy|#169);'i",
        "'&#(\d+);'e"); // evaluate as php
    $replace = array("",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "");
    $text = preg_replace($search, $replace, $str);
    //$text = ereg_replace("'", "", $text);
    // $text=ereg_replace("\\", "", $text);
    return $text;
}

function CleanFileName($Raw) {
    $Raw = trim($Raw);
    $Raw = nosign($Raw);
    $RemoveChars = array("([\40])", "([^a-zA-Z0-9-])", "(-{2,})");
    $ReplaceWith = array("-", "", "-");
    return preg_replace($RemoveChars, $ReplaceWith, $Raw);
}

function checkLoginHeader() {
    global $db;
    global $config;
    $rsUser = $db->query_first("SELECT username, password FROM user WHERE username='" . filter($_SESSION['username']) . "' AND password='" . filter($_SESSION['password']) . "' AND active=1");
    if (!$rsUser) {
        $location = $config['domain'] . '/' . $config['admin_section'] . '/login';
        header("Location: $location");
    }
}

function cutString($str, $len) {
    $last_space = mb_strrpos($temp, ' ');
    if (mb_strlen($str) > $len) {
        $temp = mb_substr($str, 0, $len);
        $last_space = mb_strrpos($temp, ' ');
        $temp = mb_substr($temp, 0, $last_space) . ' ...';
        return $temp;
    } else {
        return $str;
    }
}

function getPathWay() {
    global $db, $config;
    $sqlCat = "SELECT id,parent_id,name,link FROM article_category WHERE link='" . $config['link'] . "'";
    $rsCat = $db->query_first($sqlCat);
    if ($_SESSION['clientActiveMenu'] != 'tag') {
        if ($rsCat['parent_id'] == 0) {
            $motName = $rsCat['name'];
            if ($_SESSION['clientActiveMenu'] == 'cata' || $_SESSION['clientActiveMenu'] == 'detail') {
                $_SESSION['pathWay'] = $motLink = $rsCat['link'];
                $strPath = '<img src="' . $config ['client_images_url'] . '/arrow3.gif"/>';
                $strPath .= '<span><a href="javascript:;" class="current">' . $motName . '</a></span>';
            } elseif ($_SESSION['clientActiveMenu'] == 'archives') {
                $strPath = '» <span id="luuTruPath">Lưu trữ</span>';
            } elseif ($_SESSION['clientActiveMenu'] == 'search') {
                $strPath = '» <span>Kết quả tìm kiếm</span>';
            }
        } else {
            $haiName = $rsCat['name'];
            $haiLink = $rsCat['link'];

            $sqlMot = "SELECT id,parent_id,name,link FROM article_category WHERE id=" . $rsCat['parent_id'];
            $rsMot = $db->query_first($sqlMot);
            $motName = $rsMot['name'];
            if ($_SESSION['clientActiveMenu'] == 'cata' || $_SESSION['clientActiveMenu'] == 'detail') {
                $_SESSION['pathWay'] = $motLink = $rsMot['link'];

                $sqlCatDetail = "SELECT id,name,link FROM article_category WHERE id=" . $rsMot['parent_id'];
                $rsCatDetail = $db->query_first($sqlCatDetail);
                if ($rsCatDetail['name'] != '') {
                    $_SESSION['pathWay'] = $rsCatDetail['link'];
                    //$strPath = '» <a href="/cata/' . $rsCatDetail['link'] . '" title="' . $rsCatDetail['name'] . '">' . $rsCatDetail['name'] . '</a>' . '» <span>' . $motName . '</span>';

                    $strPath = '<img src="' . $config ['client_images_url'] . '/arrow3.gif"/>';
                    $strPath .= '<span><a href="/cata/' . $rsCatDetail['link'] . '" title="' . $rsCatDetail['name'] . '">' . $rsCatDetail['name'] . '</a></span>';
                    if ($motName != '') {
                        $strPath .= '<img src="' . $config ['client_images_url'] . '/arrow3.gif"/>';
                        $strPath .= '<span><a href="/cata/' . $motLink . '" title="' . $motName . '" class="current">' . $motName . '</a></span>';
                    }
                } else {//detail
                    $strPath = '<img src="' . $config ['client_images_url'] . '/arrow3.gif"/>';
                    $strPath .= '<span><a href="/cata/' . $motLink . '" title="' . $motName . '">' . $motName . '</a></span>';
                    if ($haiName != '') {
                        $strPath .= '<img src="' . $config ['client_images_url'] . '/arrow3.gif"/>';
                        $strPath .= '<span><a href="/cata/' . $haiLink . '" title="' . $haiName . '" class="current">' . $haiName . '</a></span>';
                    }
                }
            } else {
                $strPath = '» <a href="/cata/' . $motLink . '" title="' . $motName . '">' . $motName . '</a>';
                if ($haiName != '') {
                    $strPath .= '» <span>' . $haiName . '</span>';
                }
            }
        }
    } else {
        $strPath .= '» <span id="tagPath">Tag</span>';
    }

    return $strPath;
}

function getCategoryByParentId($parent_id=0) {
    global $db, $config;

    if ($parent_id == 0 || $parent_id == $config['category']['phong-thuy'] || $parent_id == $config['category']['kien-truc']) {
        $sql = "SELECT * FROM article_category WHERE parent_id=$parent_id AND cat_menu=1 AND cat_active=1 ORDER BY cat_order";
        $sqlCount = "SELECT count(id) as count FROM article_category WHERE parent_id=$parent_id AND cat_menu=1 AND cat_active=1 ORDER BY cat_order";
    } else {
        $sql = "SELECT * FROM article_category WHERE parent_id=$parent_id AND cat_active=1 ORDER BY cat_order";
        $sqlCount = "SELECT count(id) as count FROM article_category WHERE parent_id=$parent_id AND cat_active=1 ORDER BY cat_order";
    }

    $rs = $db->query($sql);
    $rsCount = $db->query_first($sqlCount);
    if ($rsCount['count']) {
        return $rs;
    } else {
        return false;
    }
}

function get_cat_menu($parent_id=0) {
    global $db, $config;
    $result = array();
    $sql = "SELECT * FROM article_category WHERE parent_id=$parent_id AND cat_active=1 ORDER BY cat_order";
    $rs = $db->query($sql);
    while ($row = $db->fetch_array($rs)) {
        $arrCatId = get_cat_id_to_arr($row['id']);
        $str_cat_id = '';
        foreach ($arrCatId as $key => $arrValue) {
            if ($str_cat_id == '') {
                $str_cat_id .= $arrCatId[$key]['id'];
            } else {
                $str_cat_id .= $arrCatId[$key]['id'] . ',';
            }
        }
        if ($str_cat_id == '') {
            $sqlCount = "SELECT count(id) as numrows FROM article  WHERE cat_id = " . $row['id'] . " AND status='yes'";
        } else {
            $str_cat_id = $str_cat_id .','. $row['id'];
            $sqlCount = "SELECT count(id) as numrows FROM article  WHERE cat_id IN ($str_cat_id) AND status='yes'";
        }
        $rsCount = $db->query_first($sqlCount);

        if ($rsCount['numrows']) {
            $result[$row['id']] = $row;
            $result[$row['id']]['numrows'] = $rsCount['numrows'];
        }
    }
    //print_r($result);
    if (count($result)) {
        return $result;
    } else {
        return FALSE;
    }
}

function cut_html_string($string, $limit) {
    include_once 'cutstring.php';
    $output = new HtmlCutString($string, $limit);
    return $output->cut();
}

function nosign($str) {
    $sign = array("à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă",
        "ằ", "ắ", "ặ", "ẳ", "ẵ",
        "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ",
        "ì", "í", "ị", "ỉ", "ĩ",
        "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ"
        , "ờ", "ớ", "ợ", "ở", "ỡ",
        "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ",
        "ỳ", "ý", "ỵ", "ỷ", "ỹ", "đ",
        "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă"
        , "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ",
        "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ",
        "Ì", "Í", "Ị", "Ỉ", "Ĩ",
        "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ"
        , "Ờ", "Ớ", "Ợ", "Ở", "Ỡ",
        "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ",
        "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ",
        "Đ", "ê", "ù", "à", " ", "_");

    $unsign = array("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"
        , "a", "a", "a", "a", "a", "a",
        "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
        "i", "i", "i", "i", "i",
        "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o"
        , "o", "o", "o", "o", "o",
        "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u",
        "y", "y", "y", "y", "y",
        "d",
        "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A"
        , "A", "A", "A", "A", "A",
        "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E",
        "I", "I", "I", "I", "I",
        "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O"
        , "O", "O", "O", "O", "O",
        "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U",
        "Y", "Y", "Y", "Y", "Y",
        "D", "e", "u", "a", "-", "-");
    return strtolower(str_replace($sign, $unsign, $str));
}

function nosignTitle($str) {
    $sign = array("à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă",
        "ằ", "ắ", "ặ", "ẳ", "ẵ",
        "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ",
        "ì", "í", "ị", "ỉ", "ĩ",
        "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ"
        , "ờ", "ớ", "ợ", "ở", "ỡ",
        "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ",
        "ỳ", "ý", "ỵ", "ỷ", "ỹ", "đ",
        "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă"
        , "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ",
        "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ",
        "Ì", "Í", "Ị", "Ỉ", "Ĩ",
        "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ"
        , "Ờ", "Ớ", "Ợ", "Ở", "Ỡ",
        "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ",
        "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ",
        "Đ", "ê", "ù", "à");

    $unsign = array("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"
        , "a", "a", "a", "a", "a", "a",
        "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
        "i", "i", "i", "i", "i",
        "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o"
        , "o", "o", "o", "o", "o",
        "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u",
        "y", "y", "y", "y", "y",
        "d",
        "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A"
        , "A", "A", "A", "A", "A",
        "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E",
        "I", "I", "I", "I", "I",
        "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O"
        , "O", "O", "O", "O", "O",
        "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U",
        "Y", "Y", "Y", "Y", "Y",
        "D", "e", "u", "a");
    return str_replace($sign, $unsign, $str);
}

function replaceTitle($buffer) {
    global $config;
    $buffer = str_replace("[page_title]", $config ['site_title'], $buffer);
    $buffer = str_replace("[meta_description]", $config ['site_description'], $buffer);
    $buffer = str_replace("[meta_keyword]", $config ['site_keyword'], $buffer);
    return $buffer;
}

function paging($page, $total, $link='') {
    global $params, $config;
    if ($total > 1) {
        if ($page != 1) {
            $dau = $page - 3;
            if ($dau <= 0) {
                $dau = 1;
                $dit = 3 - $page;
            }
            $dit = $dit + $page + 3;
            if ($dit > $total) {
                $dit = $total;
                $dau = $total - 6;
                if ($dau <= 0) {
                    $dau = 1;
                }
            }
        } else {
            $dau = 1;
            $dit = 6;
            if ($dit > $total) {
                $dit = $total;
            }
        }
        if ($page > $total) {
            $dau = 1;
            $dit = 1;
        }

        switch ($_SESSION['clientActiveMenu']) {
            case 'cata':
                for ($i = $dau; $i <= $dit; $i++) {
                    if ($i == $page) {
                        $pages.='<li><a href="javascript:;" class="current">' . $i . '</a></li>';
                    } else {
                        if ($i == 1) {
                            $pages.='<li><a href="/cata/' . $link . '">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/cata/' . $link . '/page/' . $i . '">' . $i . '</a></li>';
                        }
                    }
                }
                if ($page == 1) {
                    //echo '<li class="end"><a href="javascript:;" class="prev" >&laquo; First</a></li>';
                } else {
                    //echo '<li class="end"> <a href="/cata/' . $link . '/" class="prev">&laquo; First</a></li>';
                }

                echo $pages;
                if ($page == $total) {
                    // echo '<li class="end"><a href="javascript:;" class="next">Last &raquo;</a></li>';
                } else {
                    //echo '<li class="end"><a href="/cata/' . $link . '/page/' . $total . '" class="next">Last &raquo;</a></li>';
                }
                break;
            case 'topread':
                for ($i = $dau; $i <= $dit; $i++) {
                    if ($i == $page) {
                        $pages.='<li><a href="javascript:;" class="currentpage">' . $i . '</a></li>';
                    } else {
                        $pages.='<li><a href="/topread/page/' . $i . '">' . $i . '</a></li>';
                    }
                }
                if ($page == 1) {
                    echo '<li><a href="javascript:;" class="prevnext disablelink">&laquo; First</a></li>';
                } else {
                    echo '<li><a href="/topread/page/1" class="prevnext">&laquo; First</a></li>';
                }

                echo $pages;
                if ($page == $total) {
                    echo '<li><a href="javascript:;" class="prevnext disablelink">Last &raquo;</a></li>';
                } else {
                    echo '<li><a href="/topread/page/' . $total . '" class="prevnext">Last &raquo;</a></li>';
                }
                break;
            case 'search':
                for ($i = $dau; $i <= $dit; $i++) {
                    if ($i == $page) {
                        $pages.='<li><a href="javascript:;" class="current">' . $i . '</a></li>';
                    } else {
                        if ($i == 1) {
                            $pages.='<li><a href="/search/' . htmlentities(str_replace("\\", "", $config['keyword']), ENT_QUOTES, "UTF-8") . '">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/search/' . htmlentities(str_replace("\\", "", $config['keyword']), ENT_QUOTES, "UTF-8") . '/page/' . $i . '">' . $i . '</a></li>';
                        }
                    }
                }
                if ($page == 1) {
                    //echo '<li><a href="javascript:;" class="first">&laquo; First</a></li>';
                } else {
                    //echo '<li><a href="/search/' . htmlentities(str_replace("\\", "", $config['keyword']), ENT_QUOTES, "UTF-8") . '/page/1" class="first">&laquo; First</a></li>';
                }

                echo $pages;
                if ($page == $total) {
                    //echo '<li><a href="javascript:;" class="last">Last &raquo;</a></li>';
                } else {
                    //echo '<li><a href="/search/' . htmlentities(str_replace("\\", "", $config['keyword']), ENT_QUOTES, "UTF-8") . '/page/' . $total . '" class="last">Last &raquo;</a></li>';
                }
                break;

            case 'tag':
                for ($i = $dau; $i <= $dit; $i++) {
                    if ($i == $page) {
                        $pages.='<li><a href="javascript:;" class="current">' . $i . '</a></li>';
                    } else {
                        $pages.='<li><a href="/tag/' . $link . '/page/' . $i . '">' . $i . '</a></li>';
                    }
                }
                if ($page == 1) {
                    // echo '<li><a href="javascript:;" class="prevnext disablelink">&laquo; First</a></li>';
                } else {
                    echo '<li class="end"><a href="/tag/' . $link . '/page/1" class="first">&laquo; First</a></li>';
                }

                echo $pages;
                if ($page == $total) {
                    // echo '<li><a href="javascript:;" class="prevnext disablelink">Last &raquo;</a></li>';
                } else {
                    echo '<li class="end"><a href="/tag/' . $link . '/page/' . $total . 'here' . '" class="last">Last &raquo;</a></li>';
                }
                break;
            default :
                for ($i = $dau; $i <= $dit; $i++) {
                    if ($i == $page) {
                        $pages.='<li><a href="javascript:;" class="current">' . $i . '</a></li>';
                    } else {
                        if ($i == 1) {
                            $pages.='<li><a href="/">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/home_' . $i . '">' . $i . '</a></li>';
                        }
                    }
                }
                if ($page == 1) {
                    //echo '<li class="end"><a href="javascript:;" class="prev" >&laquo; First</a></li>';
                } else {
                    //echo '<li class="end"> <a href="/" class="prev">&laquo; First</a></li>';
                }

                echo $pages;
                if ($page == $total) {
                    // echo '<li class="end"><a href="javascript:;" class="next">Last &raquo;</a></li>';
                } else {
                    //echo '<li class="end"><a href="/home_' . $total . '" class="next">Last &raquo;</a></li>';
                }
                break;
        }
    } else {
        return false;
    }
}

function pagingAdmin($page, $total, $id='', $name='') {
    global $config;
    if ($total > 1) {
        if ($page != 1) {
            $dau = $page - 5;
            if ($dau <= 0) {
                $dau = 1;
                $dit = 5 - $page;
            }
            $dit = $dit + $page + 5;
            if ($dit > $total) {
                $dit = $total;
                $dau = $total - 10;
                if ($dau <= 0) {
                    $dau = 1;
                }
            }
        } else {
            $dau = 1;
            $dit = 10;
            if ($dit > $total) {
                $dit = $total;
            }
        }
        if ($page > $total) {
            $dau = 1;
            $dit = 1;
        }

        switch ($_SESSION['adminActiveMenu']) {
            case 'article':
                if ($_GET['searchArticleSubmit'] == 'Search' AND $_GET['articleActionType'] == 'searchArticle') {
                    for ($i = $dau; $i <= $dit; $i++) {
                        if ($i == $page) {
                            $pages.='<li><a href="#" class="currentpage">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/' . $config['admin_section'] . '/article/' . $i . '&searchKeyword=' . $_GET['searchKeyword'] . '&articleActionType=searchArticle&dateFrom=' . $_GET['dateFrom'] . '&dateTo=' . $_GET['dateTo'] . '&categoryId=' . $_GET['categoryId'] . '&searchArticleSubmit=Search">' . $i . '</a></li>';
                        }
                    }
                    if ($page == 1) {
                        echo '<li><a href="#" class="prevnext disablelink">&laquo; First</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/article/1&searchKeyword=' . $_GET['searchKeyword'] . '&articleActionType=searchArticle&dateFrom=' . $_GET['dateFrom'] . '&dateTo=' . $_GET['dateTo'] . '&categoryId=' . $_GET['categoryId'] . '&searchArticleSubmit=Search" class="prevnext">&laquo; First</a></li>';
                    }

                    echo $pages;
                    if ($page == $total) {
                        echo '<li><a href="#" class="prevnext disablelink">Last &raquo;</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/article/' . $total . '&searchKeyword=' . $_GET['searchKeyword'] . '&articleActionType=searchArticle&dateFrom=' . $_GET['dateFrom'] . '&dateTo=' . $_GET['dateTo'] . '&categoryId=' . $_GET['categoryId'] . '&searchArticleSubmit=Search" class="prevnext">Last &raquo;</a></li>';
                    }
                } else {
                    for ($i = $dau; $i <= $dit; $i++) {
                        if ($i == $page) {
                            $pages.='<li><a href="#" class="currentpage">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/' . $config['admin_section'] . '/article/' . $i . '">' . $i . '</a></li>';
                        }
                    }
                    if ($page == 1) {
                        echo '<li><a href="#" class="prevnext disablelink">&laquo; First</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/article/1" class="prevnext">&laquo; First</a></li>';
                    }

                    echo $pages;
                    if ($page == $total) {
                        echo '<li><a href="#" class="prevnext disablelink">Last &raquo;</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/article/' . $total . '" class="prevnext">Last &raquo;</a></li>';
                    }
                }

                break;
            case 'library':
                if ((trim($_GET['keyword']) != '' OR intval($_GET['categoryId']))) {
                    for ($i = $dau; $i <= $dit; $i++) {
                        if ($i == $page) {
                            $pages.='<li><a href="#" class="currentpage">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/' . $config['admin_section'] . '/library/' . $i . '?keyword=' . $_GET['keyword'] . '&categoryId=' . $_GET['categoryId'] . '">' . $i . '</a></li>';
                        }
                    }
                    if ($page == 1) {
                        echo '<li><a href="#" class="prevnext disablelink">&laquo; First</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/library/1?keyword=' . $_GET['keyword'] . '&categoryId=' . $_GET['categoryId'] . '" class="prevnext">&laquo; First</a></li>';
                    }

                    echo $pages;
                    if ($page == $total) {
                        echo '<li><a href="#" class="prevnext disablelink">Last &raquo;</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/library/' . $total . '?keyword=' . $_GET['keyword'] . '&categoryId=' . $_GET['categoryId'] . '" class="prevnext">Last &raquo;</a></li>';
                    }
                } else {
                    for ($i = $dau; $i <= $dit; $i++) {
                        if ($i == $page) {
                            $pages.='<li><a href="#" class="currentpage">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/' . $config['admin_section'] . '/library/' . $i . '">' . $i . '</a></li>';
                        }
                    }
                    if ($page == 1) {
                        echo '<li><a href="#" class="prevnext disablelink">&laquo; First</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/library/1" class="prevnext">&laquo; First</a></li>';
                    }

                    echo $pages;
                    if ($page == $total) {
                        echo '<li><a href="#" class="prevnext disablelink">Last &raquo;</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/library/' . $total . '" class="prevnext">Last &raquo;</a></li>';
                    }
                }

                break;
            case 'comment':
                if (isset($_GET['commentActionType']) && isset($_GET['id'])) {
                    for ($i = $dau; $i <= $dit; $i++) {
                        if ($i == $page) {
                            $pages.='<li><a href="#" class="currentpage">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/' . $i . '?id=' . $_GET['id'] . '&commentActionType=viewComment">' . $i . '</a></li>';
                        }
                    }
                    if ($page == 1) {
                        echo '<li><a href="#" class="prevnext disablelink">&laquo; First</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/1?id=' . $_GET['id'] . '&commentActionType=viewComment" class="prevnext">&laquo; First</a></li>';
                    }

                    echo $pages;
                    if ($page == $total) {
                        echo '<li><a href="#" class="prevnext disablelink">Last &raquo;</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/' . $total . '?id=' . $_GET['id'] . '&commentActionType=viewComment" class="prevnext">Last &raquo;</a></li>';
                    }
                } else {
                    for ($i = $dau; $i <= $dit; $i++) {
                        if ($i == $page) {
                            $pages.='<li><a href="#" class="currentpage">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/' . $i . '">' . $i . '</a></li>';
                        }
                    }
                    if ($page == 1) {
                        echo '<li><a href="#" class="prevnext disablelink">&laquo; First</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/1" class="prevnext">&laquo; First</a></li>';
                    }

                    echo $pages;
                    if ($page == $total) {
                        echo '<li><a href="#" class="prevnext disablelink">Last &raquo;</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/' . $total . '" class="prevnext">Last &raquo;</a></li>';
                    }
                }
                break;
            case 'question':
                if (isset($_GET['action']) && isset($_GET['id'])) {
                    $arrUrl = explode('?', $_SERVER['REQUEST_URI']);
                    $currentUrl = $arrUrl[0];
                    for ($i = $dau; $i <= $dit; $i++) {
                        if ($i == $page) {
                            $pages.='<li><a href="#" class="currentpage">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="' . $currentUrl . '?action=' . $_GET['action'] . '&id=' . $_GET['id'] . '&page=' . $i . '">' . $i . '</a></li>';
                        }
                    }
                    if ($page == 1) {
                        echo '<li><a href="#" class="prevnext disablelink">&laquo; First</a></li>';
                    } else {
                        echo '<li><a href="' . $currentUrl . '?action=' . $_GET['action'] . '&id=' . $_GET['id'] . '" class="prevnext">&laquo; First</a></li>';
                    }

                    echo $pages;
                    if ($page == $total) {
                        echo '<li><a href="#" class="prevnext disablelink">Last &raquo;</a></li>';
                    } else {
                        echo '<li><a href="' . $currentUrl . '?action=' . $_GET['action'] . '&id=' . $_GET['id'] . '&page=' . $total . '" class="prevnext">Last &raquo;</a></li>';
                    }
                } else {
                    $param_get = '';
                    if (isset($_GET['keyword'])) {
                        $param_get = "?keyword=" . $_GET['keyword'];
                    }
                    for ($i = $dau; $i <= $dit; $i++) {
                        if ($i == $page) {
                            $pages.='<li><a href="#" class="currentpage">' . $i . '</a></li>';
                        } else {
                            $pages.='<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/' . $i . $param_get . '">' . $i . '</a></li>';
                        }
                    }
                    if ($page == 1) {
                        echo '<li><a href="#" class="prevnext disablelink">&laquo; First</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/1' . $param_get . '" class="prevnext">&laquo; First</a></li>';
                    }

                    echo $pages;
                    if ($page == $total) {
                        echo '<li><a href="#" class="prevnext disablelink">Last &raquo;</a></li>';
                    } else {
                        echo '<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/' . $total . $param_get . '" class="prevnext">Last &raquo;</a></li>';
                    }
                }
                break;
            default :
                for ($i = $dau; $i <= $dit; $i++) {
                    if ($i == $page) {
                        $pages.='<li><a href="#" class="currentpage">' . $i . '</a></li>';
                    } else {
                        $pages.='<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/' . $i . '">' . $i . '</a></li>';
                    }
                }
                if ($page == 1) {
                    echo '<li><a href="#" class="prevnext disablelink">&laquo; First</a></li>';
                } else {
                    echo '<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/1" class="prevnext">&laquo; First</a></li>';
                }

                echo $pages;
                if ($page == $total) {
                    echo '<li><a href="#" class="prevnext disablelink">Last &raquo;</a></li>';
                } else {
                    echo '<li><a href="/' . $config['admin_section'] . '/' . $_SESSION['adminActiveMenu'] . '/' . $total . '" class="prevnext">Last &raquo;</a></li>';
                }
                break;
        }
    } else {
        return false;
    }
}

//'137-113','357-266',' 220-166'
function createThumb($image, $size='137-113') {
    //$static_domain = "http://bantinnhadat.vn";
    $static_domain = "";
    $img = $static_domain . $image;
    $posMedia = strpos($img, 'media.php');

    if ($img == '') {
        if ($size == '137-113') {
            return $static_domain . '/uploads/house137113.jpg';
        } elseif ($size == '47-47') {
            return $static_domain . '/uploads/house4747.jpg';
        } elseif ($size == '357-266') {
            return $static_domain . '/uploads/house107106.jpg';
        }
    } else {
        if ($size == '357-266') {//hien thi tren front page
            if ($posMedia == FALSE) {
                if (file_exists($_SERVER ['DOCUMENT_ROOT'] . str_replace('thumb-137-113', 'thumb-357-266', $image))) {
                    return str_replace('thumb-137-113', 'thumb-357-266', $image);
                } else {
                    return $static_domain . '/media.php?src=' . str_replace('thumb-137-113/', '', $image) . '&zc=1&q=80&w=357&h=266';
                }
            } else {
                return $static_domain . '/media.php?src=' . str_replace('thumb-137-113/', '', $image) . '&zc=1&q=80&w=357&h=266';
            }
        } elseif ($size == '220-166') {
            if ($posMedia == FALSE) {
                if (file_exists($_SERVER ['DOCUMENT_ROOT'] . str_replace('thumb-137-113', 'thumb-220-166', $image))) {
                    return str_replace('thumb-137-113', 'thumb-220-166', $image);
                } else {
                    return $static_domain . '/media.php?src=' . str_replace('thumb-137-113/', '', $image) . '&zc=1&q=80&w=220&h=166';
                }
            } else {
                return $static_domain . '/media.php?src=' . str_replace('thumb-137-113/', '', $image) . '&zc=1&q=80&w=220&h=166';
            }
        } elseif ($size == '137-113') {
            return $img;
        }
    }
}

function viewTitleLink($string) {
    return htmlentities($string, ENT_COMPAT, 'UTF-8');
}

function checkPermission() {
    global $db;
    $username = $_SESSION['username'];
    $sql = "SELECT deny_modules FROM permission WHERE username='$username'";
    $rsModules = $db->query($sql);
    while ($rs = $db->fetch_array($rsModules)) {
        $arrDenyModules[] = $rs['deny_modules'];
    }
    if (in_array($_SESSION['adminActiveMenu'], $arrDenyModules)) {
        echo 'Sory, bạn không có quyền truy cập trang này, Click vào <INPUT TYPE="BUTTON" VALUE=" đây " ONCLICK="history.go(-1);"> để quay lại trang trước!';
        die;
    }
}

/*
  function createThumb($img,$strFind='',$strReplace='') {
  $pos = strpos($img, 'media.php');
  if($img!='') {
  if($strReplace!='') {
  return str_replace($strFind, $strReplace, $img);
  }else {
  return $img;
  }
  }else {
  if($strReplace!='') {
  return str_replace('w=137&h=113', $strReplace, '/media.php?src=/uploads/house.jpg&zc=1&q=80&w=137&h=113');
  }else {
  return '/media.php?src=/uploads/house.jpg&zc=1&q=80&w=137&h=113';
  }
  }
  } */

function get_date_vn_now() {
    $thu = date("D", time());
    switch ($thu) {
        case 'Mon': $thu = "Thứ Hai";
            break;
        case 'Tue': $thu = "Thứ Ba";
            break;
        case 'Wed': $thu = "Thứ Tư";
            break;
        case 'Thu': $thu = "Thứ Năm";
            break;
        case 'Fri': $thu = "Thứ Sáu";
            break;
        case 'Sat': $thu = "Thứ Bẩy";
            break;
        case 'Sun': $thu = "Chủ Nhật";
            break;
    }
    return $thu . ", " . date('d/m/Y h:i', time());
}

function getDateLink($create_date) {
    $date = getdate(strtotime($create_date));
    switch ($date['wday']) {
        case 1: $thu = "Thứ Hai";
            break;
        case 2: $thu = "Thứ Ba";
            break;
        case 3: $thu = "Thứ Tư";
            break;
        case 4: $thu = "Thứ Năm";
            break;
        case 5: $thu = "Thứ Sáu";
            break;
        case 6: $thu = "Thứ Bẩy";
            break;
        case 0: $thu = "Chủ Nhật";
            break;
    }
    $title = $thu . ", " . date('d/m/Y', strtotime($create_date));
    $link = '/' . date('Y/m', strtotime($create_date));
    return array('title' => $title, 'link' => $link);
}

function print_gzipped_page() {

    global $HTTP_ACCEPT_ENCODING;
    if (headers_sent()) {
        $encoding = false;
    } elseif (strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) {
        $encoding = 'x-gzip';
    } elseif (strpos($HTTP_ACCEPT_ENCODING, 'gzip') !== false) {
        $encoding = 'gzip';
    } else {
        $encoding = false;
    }

    if ($encoding) {
        $contents = ob_get_contents();
        ob_end_clean();
        header('Content-Encoding: ' . $encoding);
        print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
        $size = strlen($contents);
        $contents = gzcompress($contents, 9);
        $contents = substr($contents, 0, $size);
        print($contents);
        exit();
    } else {
        ob_end_flush();
        exit();
    }
}

function echo_memory_usage() {
    $mem_usage = memory_get_usage(true);
    if ($mem_usage < 1024)
        echo $mem_usage . " bytes";
    elseif ($mem_usage < 1048576)
        echo round($mem_usage / 1024, 2) . " kilobytes";
    else
        echo round($mem_usage / 1048576, 2) . " megabytes";

    echo "<br/>";
}

function getCountMenu() {
    global $db;
    
    $sqlComment = "SELECT count(id) as count FROM comment WHERE status='no'";
    $rsComment = $db->query_first($sqlComment);

    $sqlOpentQ = "SELECT count(id) as count FROM question WHERE active=0";
    $rsOpenQ = $db->query_first($sqlOpentQ);

    $sqlOpentA = "SELECT count(id) as count FROM answer WHERE active=0";
    $rsOpenA = $db->query_first($sqlOpentQA);
    
    return array('comment' => $rsComment['count'],
        'openq' => $rsOpenQ['count'],
        'opena' => $rsOpenA['count']
    );
}

function lastestArticle($limit=20) {
    global $db;
    $sql = "SELECT title,link,image,short_description FROM article WHERE status='yes' ORDER BY create_date DESC LIMIT $limit";
    return $db->query($sql);
}

function getLastestArticlesByCategoryId($categoryId) {
    global $db;
    $arrCatId = get_cat_id_to_arr($categoryId);
    $str_cat_id = '';
    for ($i = 0; $i < count($arrCatId); $i++) {
        if ($i == (count($arrCatId) - 1)) {
            $str_cat_id .= $arrCatId[$i];
        } else {
            $str_cat_id .= $arrCatId[$i] . ',';
        }
    }
    if ($str_cat_id == '') {
        $sql = "SELECT a.title,a.image,a.link,a.short_description,c.name as cat_name, c.link as cat_link FROM article a LEFT JOIN article_category c
            ON a.cat_id = c.id WHERE a.cat_id=" . intval($categoryId) . " AND a.status='yes' ORDER BY a.create_date DESC";
    } else {
        $sql = "SELECT a.title,a.image,a.link,a.short_description,c.name as cat_name, c.link as cat_link FROM article a LEFT JOIN article_category c
            ON a.cat_id = c.id WHERE a.cat_id=" . intval($categoryId) . " OR a.cat_id IN ($str_cat_id) AND a.status='yes' ORDER BY a.create_date DESC";
    }

    $rs = $db->query_first($sql);
    return $rs;
}

function get_cat_id_to_arr($parent_id = 0, $trees=null) {
    global $db;
    if (!$trees)
        $trees = array();
    $rsCat = $db->query("SELECT * FROM article_category WHERE  parent_id = " . intval($parent_id));
    if ($rsCat) {
        while ($rs = $db->fetch_array($rsCat)) {
            $trees[$rs['id']] = $rs;
            $trees = get_cat_id_to_arr($rs['id'], $trees);
        }
    }
    return $trees;
}

function getArticleByCategoryIdOffsetLimit($categoryId, $offset=0, $limit=10) {
    global $db;
    $arrCatId = get_cat_id_to_arr($categoryId);
    $str_cat_id = '';
    for ($i = 0; $i < count($arrCatId); $i++) {
        if ($i == (count($arrCatId) - 1)) {
            $str_cat_id .= $arrCatId[$i];
        } else {
            $str_cat_id .= $arrCatId[$i] . ',';
        }
    }
    if ($str_cat_id == '') {
        $sql = "SELECT id,title,link FROM article WHERE cat_id=" . intval($categoryId) . " AND status='yes' ORDER BY create_date DESC LIMIT $offset,$limit";
    } else {
        $sql = "SELECT id,title,link FROM article WHERE cat_id=" . intval($categoryId) . " OR cat_id IN ($str_cat_id) AND status='yes' ORDER BY create_date DESC LIMIT $offset,$limit";
    }

    $rs = $db->query($sql);
    return $rs;
}

function addEditRelateBox($acId, $relate_for = 'article') {
    global $db;
    if (intval($acId)) {
        $view_type = $_POST['view_type'];
        if (!isset($_POST['view_type'])) {
            $view_type = $_POST['edit_view_type'];
        }
        $box_title = trim(filter($_POST['box_title']));
        if ($view_type == 'html') {
            $value = trim(mysql_escape_string($_POST['value_html']));
        } else {
            $value = implode(',', $_POST['articleSelect']);
        }

        if (!empty($box_title) && !empty($value)) {
            $data = array();
            $data['art_cat_id'] = $acId;
            $data['box_title'] = $box_title;
            $data['value'] = $value;
            $data['relate_for'] = $relate_for;
            $data['view_type'] = $view_type;
            $data['active'] = $active = intval($_POST['rbActive']);

            $rbId = intval($_POST['rbId']);
            if ($rbId) {
                $sql = "UPDATE box_relation SET art_cat_id=$acId,box_title='$box_title',value='$value',relate_for='$relate_for',view_type='$view_type',active=$active WHERE 1 AND id=$rbId";
            } else {
                $sql = "INSERT INTO box_relation (art_cat_id,box_title,value,relate_for,view_type,active) VALUES ($acId,'$box_title','$value','$relate_for','$view_type',$active)";
            }
            $db->query($sql);
        }
    }
}

//get current link
function getLinkCurrent() {
    global $db, $config;
    $sqlCat = "SELECT id,parent_id,name,link FROM article_category WHERE link='" . $config['link'] . "'";
    $rsCat = $db->query_first($sqlCat);
    if ($_SESSION['clientActiveMenu'] != 'tag') {
        if ($rsCat['parent_id'] == 0) {
            $motName = $rsCat['name'];
            if ($_SESSION['clientActiveMenu'] == 'cata' || $_SESSION['clientActiveMenu'] == 'detail') {
                $motLink = $rsCat['link'];
                $strPath = $motLink;
            }
        } else {
            $haiName = $rsCat['name'];
            $haiLink = $rsCat['link'];

            $sqlMot = "SELECT id,parent_id,name,link FROM article_category WHERE id=" . $rsCat['parent_id'];
            $rsMot = $db->query_first($sqlMot);

            $motName = $rsMot['name'];
            if ($_SESSION['clientActiveMenu'] == 'cata' || $_SESSION['clientActiveMenu'] == 'detail') {
                $motLink = $rsMot['link'];
                if ($rsMot['id'] == $config['category']['van-ban-phap-luat']) {
                    $strPath = 'luat-bat-dong-san/van-ban-phap-luat';
                } elseif ($rsMot['id'] == $config['category']['bang-bieu-mau']) {
                    $strPath = 'luat-bat-dong-san/bang-bieu-mau';
                } else {
                    $sqlCatDetail = "SELECT id,name,link,parent_id FROM article_category WHERE id=" . $rsMot['id'];
                    $rsCatDetail = $db->query_first($sqlCatDetail);
                    //var_dump($rsCatDetail);die;
                    //                if ($rsCatDetail['name'] != '' && $rsCatDetail['parent_id'] != 0) {
                    //                   echo $strPath = $rsCatDetail['link'] . '/' . $haiLink;
                    //                } else
                    if ($rsCatDetail['id'] == $config['category']['phong-thuy'] || $rsCatDetail['id'] == $config['category']['kien-truc']) {
                        $strPath = $haiLink;
                    } else {
                        //detail
                        $strPath = $motLink;
                        if ($haiName != '') {
                            $strPath = $motLink . '/' . $haiLink;
                        }
                    }
                }
            }
        }
    }
    return $strPath;
}

function showImgByFile($type = '') {
    switch ($type) {
        case "rar":
            echo 'rar.gif';
            break;
        case "zip":
            echo 'zip.gif';
            break;
        case "pdf":
            echo 'pdf.gif';
            break;
        case "xls":
            echo 'xls.gif';
            break;
        case "ppt":
            echo 'ppt.gif';
            break;
        default :
            echo 'doc.gif';
    }
}

function getCurrentUrl() {
    $curpageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {
        $curpageURL.= "s";
    }
    $curpageURL.= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $curpageURL.= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $curpageURL.= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $curpageURL;
}

function get_week_start() {
    $day = date('d');
    $month = date('m');
    $year = date('Y');
    $timestamp = mktime(0, 0, 0, $month, $day, $year);
    return $timestamp = mktime(0, 0, 0, $month, date('d', $timestamp) - date('w', $timestamp), $year);
}

function get_week_end() {
    return get_week_start() + 518400;
}

?>
